<template>
  <div>
    <!-- navbar -->
    <!-- 只需登录，用路由返回 -->
    <van-nav-bar title="登录" left-arrow @click-left="$router.back()" />
    <!-- 表单验证 -->
    <van-form
      :show-error="false"
      :show-error-message="false"
      validate-first
      ref="formRef"
      @submit="onLogin"
      @failed="onFailed"
    >
      <van-field
        v-model="user.mobile"
        icon-prefix="iconfont"
        left-icon="shouji"
        name="mobile"
        placeholder="请输入手机号"
        :rules="mobileRules"
        center
      >
        <!-- 自定义图标使用，添加类名，类名前缀-->
        <van-icon
          class="iconfont"
          class-prefix="icon"
          slot="left-icon"
          name="shouji"
        ></van-icon>
      </van-field>
      <van-field
        v-model="user.code"
        clearable
        name="code"
        placeholder="请输入验证码"
        :rules="codeRules"
        center
      >
        <!-- 自定义图标使用，添加类名，类名前缀-->
        <van-icon
          class="iconfont"
          class-prefix="icon"
          slot="left-icon"
          name="yanzhengma"
        ></van-icon>
        <!-- 发送验证码按钮 -->
        <template #button>
          <!-- 显示倒计时和发送按钮 -->
          <van-count-down
            format="ss s"
            :time="60 * 1000"
            v-if="timeShow"
            @finish="timeShow = false"
          />
          <van-button
            v-else
            size="small"
            type="default"
            round
            @click.prevent="onSendText"
            :loading="isSending"
            >获取验证码</van-button
          >
        </template>
      </van-field>
      <div class="login-btn-con">
        <van-button type="info" block class="login-btn">登录</van-button>
      </div>
    </van-form>
    <p>万能验证码：246810</p>
  </div>
</template>

<script>
export default {
  name: 'LoginIndex',
  data () {
    return {
      user: {
        mobile: '13611111111',
        code: '246810'
      },
      mobileRules: [{
        required: true, message: '请输入手机号'
      },
      {
        pattern: /^1[3|1|5|7|8|9]\d{9}$/, message: '格式错误！'
      }],
      codeRules: [{
        required: true, message: '请输入验证码'
      }, {
        // pattern 正则表达式
        pattern: /\d{6}/, message: '验证码格式错误！'
      }],
      // 倒计时显示控制
      timeShow: false,
      // 是否点击了发送，防止多次点击
      isSending: false
    }
  },
  methods: {
    // 获取登录
    async onLogin () {
      // 加载提示
      this.$toast.loading({
        message: '加载中...',
        // 加载时禁止点击背景其他区域
        forbidClick: true,
        duration: 0
      })
      try {
        const res = await this.$https.post('/app/v1_0/authorizations', this.user)
        if (res.status === 201) { this.$toast.success('登录成功！') }
        // 登陆成功后将用户信息的token保存在vuex中
        this.$store.commit('setUser', res.data.data)
        this.$router.push('/my')
      } catch (error) {
        console.dir(error)
        this.$toast.fail('登录失败！验证码或手机错误')
      }
    },
    // 表单验证不通过的错误提示
    onFailed (err) {
      this.$toast({
        message: err.errors[0].message,
        // 提示消息位置设置
        position: 'top'
      })
    },
    // 获取验证码的手机号校验
    async onSendText () {
      this.isSending = true
      try {
        await this.$refs.formRef.validate('mobile')
        await this.$https.get(`/app/v1_0/sms/codes/${this.user.mobile}`)
        this.timeShow = true
      } catch (error) {
        let message = ''
        // 发送频繁的错误信息
        console.dir(error)
        if (error.response.status === 429) {
          message = '发送太频繁，请稍后重试！'
          console.log('???')
        } else if (error.name === 'mobile') {
          // 手机号码验证失败的错误提示信息
          message = error.message
          // 未知错误
        } else { message = '发送失败，请稍后重试！' }
        this.$toast({
          message,
          position: 'top'
        })
      }
      // 不论成功失败都需关闭
      this.isSending = false
    }
  }
}
</script>

<style scoped>
.login-btn-con {
  padding: 26px 16px;
}
.login-btn {
  background-color: aqua;
  border-radius: 3px;
  border: none;
}
p {
  font-size: 16px;
  text-align: center;
  color: #ccc;
}
</style>
